
#include "../includes.h"

#include "FPGAdata.h"


void fpga_init(int fd)
{
int i,j,k=0;
unsigned char temp;
int size;
//int FPGA_DATASIZE = (&FPGA_Data_end[0] - &FPGA_Data[0]);	//sewon
//int FPGADATASIZE = FPGA_DATASIZE*4; 							//sewon
//unsigned char FPGAData[FPGADATASIZE];							//sewon
//int shift[4] = {0x000000FF,0x0000FF00,0x00FF0000,0XFF000000};//sewon
int oneof10=(int)(FPGADATASIZE/10);
int l;
/*
	for(i=0;i<FPGA_DATASIZE;i++)		//sewon FPGA_Data(4byte) -> FPGAData(1byte) Change
	{
		for(j=0;j<4;j++)
		{
			FPGAData[(i*4)+j] = (shift[j%4]&FPGA_Data[i])>>(8*(j%4));
//       FPGAData[(i*4)+j]&=0x000000FF;
//			printf("0x%.2x, ",FPGAData[(i*4)+j]);
		}
//		if(((i+1)%2==0)) printf("\n");
	}

	for(l=0;l<1000;l++)		//sewon FPGAData Print
	{
		printf("0x%.2x, ",FPGAData[l]);

		if((l+1)%8==0)		printf(" | ");
		if((l+1)%16==0)	printf("\n");
	}
*/
	printf("\n>>FPGADATASIZE : %d\n",FPGADATASIZE);

	SetFPGAData();	//set as output
	SetFPGAClk();	//set as output
	SetFPGAProg();	//set as output
	SetFPGADone();	//set as input	
	
	SetFPGAmLatch();	//set as output
	SetFPGAmClear();	//set as output
	SetFPGAmClearLow();
	SetFPGAmLatchLow();

	SetDACPort();		//set DAC port
	
	SetFPGAProgHigh();
	
	msleep(20);
	
	SetFPGAProgLow();
	SetFPGAProgHigh();
	msleep(80);

	if( GetFPGADone() == 1 ){printf("FPGA Done Fail... !!\r\n");}
	else {printf("FPGA Done Ok... !!!\r\n");}
	
	msleep(100);
	
	size = write( fd,(char *)FPGAData, FPGADATASIZE );	//sewon
	
	msleep(100);

	if( GetFPGADone() == 1 ){printf("FPGA Prog (%d) OK... !!!\r\n",size);}
	else {printf("FPGA Prog Error... !!!\r\n");}
	
	strcpy(FPGA_Version,FPGA_VERSION_STRING);
}


void ChangeDACValue(int fd, int volt)
{
    int i;
	
    SetDacCsLow(fd); 
	
	if( volt > 65534 ) volt = 65534;
	else if( volt < 0 ) volt = 0 ;	
	
    for( i = 0; i < 16; i++){

        SetDacClkLow(fd); 
        
        if (((volt<<i)&0x8000)) {SetDacDinHigh(fd);}
        else {SetDacDinLow(fd);}
        	
        SetDacClkHigh(fd); 
    }

    SetDacCsHigh(fd); 
	ave_PushValue(&ave_dac, (double)volt);
}
